// pages/driver/driverJoining/driverJoining.ts
// @ts-ignore
import { getJSZ, getXSZ } from '../../../http/api/userServiceApi'
import { driverJoining } from '../../../http/api/driverService'
import { obtainVehicleType } from '../../../http/api/positionApi'

const { Config } = require('../../../lib/config')
// @ts-ignore
const BASE_URL = Config.BASE_URL
Page({
    /**
     * 页面的初始数据
     */
    data: {
        userInfo: {},
        autosize: {
            maxHeight: 600,
            minHeight: 20
        },

        carText: '',
        carValue: [],
        cars: [{ label: '北京市', value: '北京市' }],

        jsList: [],
        jsInfo: {},
        jsStr: '',
        jsUrl: '',

        xsFrontList: [],
        xsFrontInfo: {},
        xsFrontStr: '',
        xsFrontUrl: '',

        xsBackList: [],
        xsBackInfo: {},
        xsBackStr: '',
        xsBackUrl: ''
    } as any,

    onPickerChange(e: any) {
        const { key } = e.currentTarget.dataset
        const { value, columns } = e.detail

        console.log('picker change:', e.detail, columns[0].index)
        this.setData({
            [`${key}Visible`]: false,
            [`${key}Value`]: this.data.cars[columns[0].index].id,
            [`${key}Text`]: value.join(' ')
        })
    },

    onPickerCancel(e: any) {
        const { key } = e.currentTarget.dataset
        console.log(e, '取消')
        console.log('picker1 cancel:')
        this.setData({
            [`${key}Visible`]: false
        })
    },

    onCarPicker() {
        this.setData({ carVisible: true })
    },

    async join() {
        const { carValue, userInfo, jsInfo, jsUrl, xsFrontInfo, xsFrontUrl, xsBackInfo, xsBackUrl } = this.data
        const info = {
            user_id: userInfo.ID,
            Driver_Number: jsInfo.id_num,
            Driver_valid_from: jsInfo.valid_from, //驾驶证有效期开始日期
            Driver_valid_to: jsInfo.valid_to,
            Driver_Photo_Url: jsUrl,

            car_id: carValue, //车型ID

            Car_Number: xsBackInfo.record, //行驶证编号
            Car_model: xsFrontInfo.model, //车型
            Car_vin: xsFrontInfo.vin, //车辆识别代号
            Car_record: xsFrontInfo.plate_num_b, //车牌
            Car_register_date: xsFrontInfo.register_date, //行驶证注册日期
            Car_issue_date: xsFrontInfo.issue_date, //行驶证发证日期

            Car_engine_num: xsFrontInfo.engine_num, //发动机号码
            Car_passengers_num: xsBackInfo.passengers_num, //核定载客数
            Car_use_character: xsFrontInfo.use_character, //车辆使用性质
            Car_Photo_Url: xsFrontUrl //行驶证照片(调用通用上传地址号后得到的地址)s
        }
        console.log(info)
        const res: any = await driverJoining(info)
        console.log(res, '加盟')
        if (res.data.data[0].msg == '提交成功') {
            wx.navigateBack()
        }
    },

    handleJSAdd(e: any) {
        const { jsList }: any = this.data
        const { files } = e.detail

        // 方法1：选择完所有图片之后，统一上传，因此选择完就直接展示
        this.setData({
            jsList: [...jsList, ...files] // 此时设置了 fileList 之后才会展示选择的图片
        })
        console.log(this.data.jsList)
        this.uploadJSFile(this.data.jsList[0])
    },
    uploadJSFile(file: any) {
        const { jsList } = this.data

        this.setData({
            jsList: [...jsList, { ...file, status: 'loading' }]
        })
        const { length } = jsList
        console.log(file.url, '-----file')
        const token = wx.getStorageSync('token')
        const openid = wx.getStorageSync('openid')
        const task = wx.uploadFile({
            url: BASE_URL + '/api/UploadFile', // 仅为示例，非真实的接口地址
            filePath: file.url,
            name: 'file',
            header: {
                token,
                openid
            },
            formData: { Files: file.url },
            success: async (res: any) => {
                const { data } = JSON.parse(res.data)
                const url = `${BASE_URL}${data[0]}`
                console.log(url, '---success')
                const JSZRes: any = await getJSZ(url)
                console.log(JSZRes, '---JSZRes')
                const str = `准驾车型: ${JSZRes.data.data[0].car_class}\n驾驶证编号: ${JSZRes.data.data[0].id_num}\n驾驶员名称: ${JSZRes.data.data[0].name}\n驾驶证有效期开始日期: ${JSZRes.data.data[0].valid_from}\n驾驶证有效期截止日期: ${JSZRes.data.data[0].valid_to}`
                this.setData({
                    [`jsList[${length}].status`]: 'done',
                    jsInfo: JSZRes.data.data[0],
                    jsStr: str,
                    jsUrl: url
                })
            },
            fail: function (error) {
                console.log(error)
            }
        })
        task.onProgressUpdate(res => {
            this.setData({
                [`jsList[${length}].percent`]: res.progress
            })
        })
    },
    handleJSRemove(e: any) {
        const { index } = e.detail
        const { jsList } = this.data

        jsList.splice(index, 1)
        this.setData({
            jsList
        })
    },

    handleXSBackAdd(e: any) {
        const { xsBackList }: any = this.data
        const { files } = e.detail

        // 方法1：选择完所有图片之后，统一上传，因此选择完就直接展示
        this.setData({
            xsBackList: [...xsBackList, ...files] // 此时设置了 fileList 之后才会展示选择的图片
        })
        console.log(this.data.xsBackList)
        this.uploadXSBackFile(this.data.xsBackList[0])
    },
    uploadXSBackFile(file: any) {
        const { xsBackList } = this.data

        this.setData({
            xsBackList: [...xsBackList, { ...file, status: 'loading' }]
        })
        const { length } = xsBackList
        console.log(file.url, '-----file')
        const token = wx.getStorageSync('token')
        const openid = wx.getStorageSync('openid')
        const task = wx.uploadFile({
            url: BASE_URL + '/api/UploadFile', // 仅为示例，非真实的接口地址
            filePath: file.url,
            name: 'file',
            header: {
                token,
                openid
            },
            formData: { Files: file.url },
            success: async (res: any) => {
                const { data } = JSON.parse(res.data)
                const url = `${BASE_URL}${data[0]}`
                console.log(url, '---success')
                const XSZRes: any = await getXSZ(url, 'BACK')
                console.log(XSZRes, '---XSZRes')
                const xszData: any = XSZRes.data.data
                const str = `承载人数:${xszData[0].passengers_num}\n档案编号:${xszData[0].record}`
                this.setData({
                    [`xsBackList[${length}].status`]: 'done',
                    xsBackInfo: XSZRes.data.data[0],
                    xsBackStr: str
                })
            },
            fail: function (error) {
                console.log(error)
            }
        })
        task.onProgressUpdate(res => {
            this.setData({
                [`xsBackList[${length}].percent`]: res.progress
            })
        })
    },
    handleXSBackRemove(e: any) {
        const { index } = e.detail
        const { xsBackList } = this.data

        xsBackList.splice(index, 1)
        this.setData({
            xsBackList
        })
    },

    handleXSFrontAdd(e: any) {
        const { xsFrontList }: any = this.data
        const { files } = e.detail

        // 方法1：选择完所有图片之后，统一上传，因此选择完就直接展示
        this.setData({
            xsFrontList: [...xsFrontList, ...files] // 此时设置了 fileList 之后才会展示选择的图片
        })
        console.log(this.data.xsFrontList)
        this.uploadXSFrontFile(this.data.xsFrontList[0])
    },
    uploadXSFrontFile(file: any) {
        const { xsFrontList } = this.data

        this.setData({
            xsFrontList: [...xsFrontList, { ...file, status: 'loading' }]
        })
        const { length } = xsFrontList
        console.log(file.url, '-----file')
        const token = wx.getStorageSync('token')
        const openid = wx.getStorageSync('openid')
        const task = wx.uploadFile({
            url: BASE_URL + '/api/UploadFile', // 仅为示例，非真实的接口地址
            filePath: file.url,
            name: 'file',
            header: {
                token,
                openid
            },
            formData: { Files: file.url },
            success: async (res: any) => {
                const { data } = JSON.parse(res.data)
                const url = `${BASE_URL}${data[0]}`
                console.log(url, '---success')
                const XSZRes: any = await getXSZ(url)
                const xszData: any = XSZRes.data.data
                console.log(data, '---XSZRes')
                const str = `车辆所有人:${xszData[0].owner}\n发动机号码:${xszData[0].engine_num}\n发证日期:${xszData[0].issue_date}\n注册日期:${xszData[0].register_date}\n品牌型号:${xszData[0].model}\n车牌:${xszData[0].plate_num_b}\n车辆识别代号:${xszData[0].vin}`
                this.setData({
                    [`xsFrontList[${length}].status`]: 'done',
                    xsFrontInfo: XSZRes.data.data[0],
                    xsFrontStr: str
                })
            },
            fail: function (error) {
                console.log(error)
            }
        })
        task.onProgressUpdate(res => {
            this.setData({
                [`xsFrontList[${length}].percent`]: res.progress
            })
        })
    },
    handleXSFrontRemove(e: any) {
        const { index } = e.detail
        const { xsFrontList } = this.data

        xsFrontList.splice(index, 1)
        this.setData({
            xsFrontList
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */ async onLoad(option: any) {
        this.setData({
            userInfo: JSON.parse(option.userInfo)
        })
        const data: any = await obtainVehicleType()
        console.log(data, '-----fata')
        const arr = data.map((item: any) => {
            return { label: item.Car_Type_Name, value: item.Car_Type_Name, id: item.ID }
        })
        this.setData({
            cars: arr
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {},

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {},

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {},

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {},

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {},

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {}
})
